package com.ai.aichat.config;

import com.ai.aichat.entity.Users;
import com.ai.aichat.mapper.UsersMapper;
import com.ai.aichat.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class UsersConfig {
    @Autowired
    private UsersMapper userMapper;
    @Autowired
    private final PasswordEncoder passwordEncoder; // 用于注册/导入用户时编码密码
    @Autowired
    private IUsersService userService;

    public UsersConfig(UsersMapper userMapper, PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return username -> {
            Users userByUsername = (Users) userService.getByUsername(username);
            if (userByUsername == null) {
                throw new UsernameNotFoundException("User not found or disabled");
            }

            return User.withUsername(username)
                    .password(userByUsername.getPassword())
                    .accountExpired(false)
                    .accountLocked(false)
                    .credentialsExpired(false)
                    .disabled(false)
                    .build();
        };
    }
}
